package com.wn.course.repository

import androidx.lifecycle.LiveData
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import com.wn.common.model.SingleLiveData
import com.wn.course.repository.api.CourseService
import com.wn.course.repository.data.CourseCategory
import com.wn.course.repository.data.Daily
import com.wn.course.utils.CustomCategory
import dagger.hilt.android.scopes.ViewModelScoped
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOn
import javax.inject.Inject

/**
 * @Author: wn
 * @Date: 2023/9/21 16:52
 * @Description: 课程模块 接口 实现类
 */
const val PAGE_SIZE = 8

@ViewModelScoped
class CourseRepository @Inject constructor(
  private val customCategory: CustomCategory,
  private val courseService: CourseService,
) : ICourseRepository {
  // 课程分类 响应数据
  private val _liveCourseType = SingleLiveData<CourseCategory>()
  override val liveCourseType: LiveData<CourseCategory> = _liveCourseType

  /**
   * 课程分类
   */
  override suspend fun getCourseCategory() {
    // 创造课程分类 数据 集合
    // 创建一个CourseCategory的实例
    val category = CourseCategory()
    customCategory.customCategoryFun(category)

    delay(10)

    _liveCourseType.value = category
  }

  /**
   * 获取课程数据
   * @return Flow<PagingData<Daily.Item>>
   */
  override fun getDaily(): Flow<PagingData<Daily.Item>> = Pager(
    PagingConfig(
      pageSize = PAGE_SIZE,
//      initialLoadSize = PAGE_SIZE * 2 // 初始加载定义请求的加载大小，通常大于 pageSize  默认 3
    )
  ) { CoursePagingSource(courseService) } // 下拉刷新-- Repository中 每次都需要 不同的 PagingSource 实例  那里无需 hilt
    .flow
    .flowOn(Dispatchers.IO)
}